<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// import JhHeader from '@/components/JhHeader.vue'
// 视频流引用
const videoRef = ref(null)
// 照片数据数组
const capturedImages = ref([])
// 是否正在使用摄像头
const isCameraActive = ref(false)
// 摄像头媒体流对象
let mediaStream = null

// 请求摄像头权限并启动摄像头
const startCamera = async () => {
  try {
    // 请求用户媒体设备权限
    mediaStream = await navigator.mediaDevices.getUserMedia({
      video: { width: 640, height: 480 },
      audio: false,
    })

    // 将摄像头视频流绑定到video元素
    if (videoRef.value) {
      videoRef.value.srcObject = mediaStream
      videoRef.value.play()
      isCameraActive.value = true
    }
  } catch (error) {
    console.error('无法访问摄像头:', error)
    alert('请确保您已授予摄像头权限')
  }
}

// 停止摄像头
const stopCamera = () => {
  if (mediaStream) {
    // 停止所有视频轨道
    mediaStream.getTracks().forEach((track) => track.stop())
    mediaStream = null
    isCameraActive.value = false
  }
}

// 拍照功能
const takePhoto = () => {
  if (!videoRef.value || !isCameraActive.value) return

  // 创建canvas元素用于捕获当前视频帧
  const canvas = document.createElement('canvas')
  canvas.width = 640
  canvas.height = 480

  // 获取绘图上下文并绘制当前视频帧
  const context = canvas.getContext('2d')
  context.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height)

  // 将canvas内容转换为base64格式的图片数据
  const imageData = canvas.toDataURL('image/jpeg')

  // 将照片添加到已捕获照片数组中
  capturedImages.value.push({
    id: Date.now(),
    data: imageData,
    timestamp: new Date().toLocaleString(),
  })
}

// 下载照片到本地
const downloadPhoto = (imageData, index) => {
  // 创建一个临时链接元素
  const link = document.createElement('a')
  link.href = imageData
  link.download = `photo_${index + 1}_${Date.now()}.jpg`

  // 模拟点击下载
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 删除照片
const deletePhoto = (id) => {
  capturedImages.value = capturedImages.value.filter((img) => img.id !== id)
}

// 组件挂载时启动摄像头
onMounted(() => {
  startCamera()
})

// 组件卸载时停止摄像头，释放资源
onUnmounted(() => {
  stopCamera()
})
</script>

<template>
  <div class="camera-container">
    <!-- <JhHeader /> -->
    <h1>摄像头拍照</h1>

    <!-- 摄像头预览区域 -->
    <div class="camera-preview">
      <video ref="videoRef" autoplay></video>
      <div class="controls">
        <button @click="takePhoto" :disabled="!isCameraActive">拍照</button>
        <button @click="isCameraActive ? stopCamera() : startCamera()">
          {{ isCameraActive ? '关闭摄像头' : '开启摄像头' }}
        </button>
      </div>
    </div>

    <!-- 已捕获照片展示区域 -->
    <div class="photos-container" v-if="capturedImages.length > 0">
      <h2>已拍摄的照片</h2>
      <div class="photos-grid">
        <div v-for="(photo, index) in capturedImages" :key="photo.id" class="photo-item">
          <img :src="photo.data" alt="拍摄的照片" />
          <p>{{ photo.timestamp }}</p>
          <div class="photo-actions">
            <button @click="downloadPhoto(photo.data, index)">下载</button>
            <button @click="deletePhoto(photo.id)" class="delete-btn">删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.camera-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
}

.camera-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

video {
  border: 2px solid #ddd;
  border-radius: 8px;
  margin-bottom: 15px;
  background-color: #000;
}

.controls {
  display: flex;
  gap: 10px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  transition: background-color 0.3s;
}

button:hover:not(:disabled) {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.delete-btn {
  background-color: #f44336;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.photos-container {
  margin-top: 30px;
}

h2 {
  color: #333;
  margin-bottom: 15px;
}

.photos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.photo-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  background-color: #f9f9f9;
}

.photo-item img {
  width: 100%;
  height: auto;
  border-radius: 4px;
  margin-bottom: 10px;
}

.photo-item p {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.photo-actions {
  display: flex;
  gap: 10px;
}

.photo-actions button {
  flex: 1;
  padding: 8px;
  font-size: 14px;
}
</style>
